<?php
/*
 * 车款类
 * @package    auto
 * @author     YuNian, mark
 * @copyright  Copyright (c) 2013 ixdcw team
 * @version    $Id: da22d5d72ab4213cd3b0ab2a7606029c0143a6d0 $
 */

/**
 * 车款显示类
 * Class AutoShowCar
 */
class AutoModel {

	const MODEL_PASSENGER  = 'passenger';
	const MODEL_COMMERCIAL = 'commercial';
	const MODEL_RV         = 'rv';

	private static $_tableModel;
	private static $_tableExts;

	/**
	 * 获取车系主表
	 * @return string
	 */
	private static function _getTableModel() {
		if (!empty(self::$_tableModel)) {
			return self::$_tableModel;
		} else {
			self::$_tableModel = Table::name(Table::NAME_AUTO_MODEL);
			return self::$_tableModel;
		}
	}

	/**
	 * 车系扩展表
	 * @param $type
	 * @return mixed
	 */
	public static function getTableExt($type) {
		if (!empty(self::$_tableExts)) {
			return self::$_tableExts[$type];
		} else {
			self::$_tableExts = array(
				self::MODEL_PASSENGER  => Table::name(Table::NAME_AUTO_MODEL_PASSENGER),
				self::MODEL_COMMERCIAL => Table::name(Table::NAME_AUTO_MODEL_COMMERCIAL),
				self::MODEL_RV         => Table::name(Table::NAME_AUTO_MODEL_RV),
			);
			return self::$_tableExts[$type];
		}
	}

	public static function getList($filter, $fileds = '*') {
		global $db;
		$condition = ' 1=1 ';
		if (isset($filter['acid'])) { // level
			$acid = AutoCategory::getCacheItem(AutoCategory::TYPE_LEVEL, $filter['acid'], 'arrchildid');
			$condition .= ' and acid in('.$acid.') ';
		}
		if (isset($filter['engine'])) { // level
			$acid = AutoCategory::getCacheItem(AutoCategory::TYPE_ENGINE, $filter['engine'], 'arrchildid');
			$condition .= ' and enginetype in('.$acid.') ';
		}
		if (isset($filter['arcid'])) { // carid
			$condition .= ' and arcid = '.$filter['arcid'];
		}
		if (isset($filter['arbid'])) { // brand
			$condition .= ' and arbid = '.$filter['arbid'];
		}
		if (isset($filter['armid'])) { // brand
			$condition .= ' and armid = '.$filter['armid'];
		}
		$sql = "select {$fileds} from ".self::_getTableModel()." where " .$condition;
		$list = array();
		$rs = $db->query($sql);
		while($r = $db->fetchArray($rs)) {
			$list[$r['amid']] = $r;
		}
		return $list;
	}


	public static function getDistinctList($filter, $filed) {
		global $db;
		$condition = ' 1=1 ';
		if (isset($filter['acid'])) { // level
			$acid = AutoCategory::getCacheItem(AutoCategory::TYPE_LEVEL, $filter['acid'], 'arrchildid');
			$condition .= ' and acid in('.$acid.') ';
		}
		if (isset($filter['engine'])) { // level
			$acid = AutoCategory::getCacheItem(AutoCategory::TYPE_ENGINE, $filter['engine'], 'arrchildid');
			$condition .= ' and enginetype in('.$acid.') ';
		}
		if (isset($filter['arcid'])) { // carid
			$condition .= ' and arcid = '.$filter['arcid'];
		}
		if (isset($filter['arbid'])) { // brand
			$condition .= ' and arbid = '.$filter['arbid'];
		}
		if (isset($filter['armid'])) { // brand
			$condition .= ' and armid = '.$filter['armid'];
		}
		$sql = "select distinct {$filed} from ".self::_getTableModel()." where " .$condition;
		$all = $db->getCol($sql, $filed);
		return $all;
	}

	/**
	 * 获取一条车款的详细信息
	 * @param $modelid
	 * @return array
	 */
	public static function get($modelid) {
		global $db;
		$sql      = "select * from " . self::_getTableModel() . " where amid=$modelid";
		$model    = $db->getOne($sql);
		$tableExt = self::getTableExt($model['modeltype']);
		$sqlExt   = "select * from $tableExt where amid = $modelid";
		$modelExt = $db->getOne($sqlExt);
		return array_merge($model, $modelExt);
	}

	/**
	 * 获取所有车款简要属性
	 * @param $carid
	 * @return array
	 */
	public static function shortByCarid($carid) {
		global $db;
		$sql    = "select * from " . self::_getTableModel() . " where status=3 and arcid=$carid";
		$result = $db->query($sql);
		$arr    = array();
		while ($r = $db->fetchArray($result)) {
			$arr[$r['amid']] = $r;
		}
		return $arr;
	}

	/**
	 * 获取所有车款简要属性
	 * @param $modelid
	 * @return array|null
	 */
	public static function shortByModelid($modelid) {
		global $db;
		$sql    = "select * from " . self::_getTableModel() . " where amid=$modelid";
		$result = $db->getOne($sql);

		return $result;
	}

	/**
	 * 根据carid获取所有详细信息
	 * @param        $carid
	 * @param string $amids
	 * @return array|null
	 */
	public static function detailByCarid($carid, $amids = '') {
		global $db;

		//假如是参数配置
		if ($carid) {
			$models = self::shortByCarid($carid);
			$amids  = (array)__($models)->pluck('amid');
			$amids  = implode(',', $amids);

			//否则就是对比页呗
		} else {
			$amidArr = explode(',', $amids);
			foreach ($amidArr as $val) {
				$models[$val] = self::shortByModelid($val);
			}
		}

		if ($models) {
			$first    = (array)__($models)->first();
			$type     = $first['modeltype'];
			$tableExt = self::getTableExt($type);
			$sql      = "select * from $tableExt where amid in($amids)";
			$result   = $db->query($sql);
			$arr      = array();
			while ($r = $db->fetchArray($result)) {
				$arr[$r['amid']] = array_merge($r, $models[$r['amid']]);
			}

			return $arr;
		} else {
			return null;
		}
	}

	public static function saleGroup($models) {
		$cIs = __($models)->groupBy('cIssale');
		foreach ($cIs as $key => $items) {
			$cIs[$key] = __($items)->groupBy('cYear');
		}
		return $cIs;
	}


	public static function translate($models) {
		return __($models)->map(function ($item) {
			$item['cIssale']   = $item['issale'] ? '在售车款' : '停售车款';
			$item['cYear']     = AutoCategory::getCacheItem(AutoCategory::TYPE_YEAR, $item['year']);
			$item['cPrice']    = Auto::formatPrice($item['price']);
			$item['cGearBox']  = AutoCategory::getCacheItem(AutoCategory::TYPE_GEARBOX, $item['gearbox']);
			$item['cEmission'] = AutoCategory::getCacheItem(AutoCategory::TYPE_EMISSION, $item['emission']);
			$item['cEngine']   = AutoCategory::getCacheItem(AutoCategory::TYPE_ENGINE, $item['enginetype']);
			$item['cCountry']  = AutoCategory::getCacheItem(AutoCategory::TYPE_COUNTRY, $item['country']);
			$item['cLevel']    = AutoCategory::getCacheItem(AutoCategory::TYPE_LEVEL, $item['acid']);
			return $item;
		});
	}

	public static function params($modelType) {
		global $db;
		$comParam = array(
			self::MODEL_PASSENGER  => 3716,
			self::MODEL_COMMERCIAL => 3733,
			self::MODEL_RV         => 3693,
		);
		$tableExt = self::getTableExt($modelType);
		$fdCom    = PCache::read('fields-' . str_replace($db->getPre(), '', self::_getTableModel()) . '.php');
		foreach ($fdCom as $k => $v) {
			$v['param_group'] = $comParam[$modelType];
		}
		$fdExt = PCache::read('fields-' . str_replace($db->getPre(), '', $tableExt) . '.php');
		$fd    = array_merge($fdCom, $fdExt);
		return $fd;
	}

	public static function paramGroup($fd) {
		$fdGroup  = __($fd)->groupBy('param_group');
		$basicAdd = array();
		foreach ($fdGroup as $dk => $dv) {
			$tmp = AutoCategory::getCacheItem(AutoCategory::TYPE_PARAM_GROUP, $dk);
			if ($tmp == '') {
				$basicAdd = $dv;
				unset($fdGroup[$dk]);
				continue;
			}
			if ($tmp == '基本参数') {
				$fdGroup[$dk] = array_merge($basicAdd, $dv);
			}
			$fdGroup[$dk]['_'] = array(
				'paramGroupId'   => $dk,
				'paramGroupName' => $tmp,
			);
		}
		return $fdGroup;
	}

	/**
	 * 格式化参数
	 * @param $models
	 * @return array
	 */
	public static function formatParams($models) {
		$modelFirst   = __($models)->first();
		$modelType    = $modelFirst['modeltype'];
		$fd           = self::params($modelType);
		$formatModels = array();
		foreach ($models as $key => $model) {
			$formatModels[$key] = AutoField::values($model, $fd);
		}
		return $formatModels;
	}

	/**
	 * 获取车款的名称
	 * @param $amid
	 * @return null
	 */
	public static function getModelName($amid) {
		global $db;
		$table = Table::name(Table::NAME_AUTO_MODEL);
		$sql   = "select name from $table where amid=$amid";
		return $db->getVar($sql);
	}

	/**
	 * 根据类型返回参数项
	 * @param $modelType
	 * @param $params
	 * @return array
	 */
	public static function paramsMain($modelType, $params) {
		$param = array();
		switch ($modelType) {
			case 'rv':
				$param = array('arbid', 'level', 'armid', 'license', 'driving_qualifications', 'shape_size', 'engine', 'transmission', 'fuel_consumption', 'emission', 'fuel_tank_capacity', 'net_water_tank_capacity', 'expansion_tank', 'living_area', 'bed_num',);
				break;
			case 'passenger':
				$param = array('price', 'armid', 'gearbox', 'acid', 'car_body_structure', 'year', 'curb_weight', 'length', 'width', 'height', 'oil_wear', 'engine_power', 'transmission_type',);
				break;
			case 'commercial':
				$param = array('price', 'arbid', 'gearbox', 'acid','emission', 'wheelbase', 'emissions', 'gear_box_type', 'emission', 'level', 'place_origin', 'max_speed', 'fuel_consumption', 'note','body_size','drever_type');
				break;
		}
		$result = array();
		foreach ($param as $key) {
			$result[$key] = $params[$key];
		}
		return $result;
	}

	/**
	 * 获取车款缩略图
	 * @param $carId
	 * @param $modelId
	 * @return array|null
	 */
	public static function getModelPicture($carId, $modelId) {
		global $db;
		$table        = Table::autoPicture($carId);
		$autoCategory = AutoCategory::getCache(AutoCategory::TYPE_PICTURE);
		foreach ($autoCategory as $val) {
			if ($val['name'] == '外观') {
				$waiguanAlid = $val['arrchildid'];
				break;
			}
		}

		//匹配车款 外观图片
		$sql = "select apid,imgurl from $table where amid=$modelId and alid in ($waiguanAlid) order by listorder DESC limit 1";
		if ($picture = $db->getOne($sql)) return $picture;

		//匹配车系 外观图片
		if (!$picture) {
			$sql = "select apid,imgurl from $table where arcid=$carId and alid in ($waiguanAlid) order by listorder DESC limit 1";
			if ($picture = $db->getOne($sql)) return $picture;
		}

		//匹配车系 任意图片
		if (!$picture) {
			$sql = "select apid,imgurl from $table where arcid=$carId order by listorder DESC limit 1";
			if ($picture = $db->getOne($sql)) return $picture;
		}
		return '';
	}


	public static function commercialSpecialNotMatched($acid) {

		// need unset Level
		$matched = array(
			454  => 3747, // 	冷藏车
			455  => 3746, // 	油罐车
			456  => 3748, // 	洒水车/喷洒车
			457  => 3749, // 	清障车
			458  => 0, // 	垃圾车
			459  => 0, // 	吸污/吸粪车
			460  => 0, // 	粉粒物料车
			461  => 0, // 	高空作业车
			462  => 0, // 	扫路车
			463  => 3751, // 	随车吊
			464  => 0, // 	消防车
			465  => 0, // 	平板运输车
			466  => 0, // 	化工液体运输车
			467  => 3750, // 	清洗车
			468  => 0, // 	教练车
			469  => 0, // 	液化气体运输车
			470  => 0, // 	除雪车
			471  => 0, // 	爆破器材运输车
			472  => 0, // 	除尘车
			473  => 0, // 	吸尘车
			474  => 3744, // 	混凝土搅拌车
			475  => 3742, // 	宽体矿用自卸车
			476  => 0, // 	矿山车
			477  => 0, // 	铰接式卡车
			478  => 3745, // 	泵车
			479  => 3751, // 	吊车
			4820 => 0, // 	农用车
			446  => 4441, // 	客车
			452  => 3743 , // 	货车
			451  => 3742 , // 	自卸车
			450  => 0, // 	牵引车
		);

		$AUTO_LEVEL = AutoCategory::getCache(AutoCategory::TYPE_LEVEL);

		// 专用车的ID
		$special = (array)__($AUTO_LEVEL)->filter(function ($item) {
			return $item['parentid'] == 453;
		});
		// 客车条目
		$acids = (array)__(array_merge($special, array($AUTO_LEVEL['446'])))->pluck('arid');

		$keys = array_keys($matched, $matched[$acid]);
		if ($keys) {
			foreach($keys as $key) {
				unset($matched[$key]);
			}
		}

		foreach($acids as $acid) {
			if (empty($matched[$acid])) {
				unset($matched[$acid]);
				continue;
			}
		}
		return array_values($matched);
	}

	/**
	 * 删除参数
	 * @param $params
	 * @param $str
	 * @return mixed
	 */
	public static function dropParam($params, $str) {
		$strs = explode(',', $str);
		foreach ($strs as $key => $param) {
			foreach ($params as $item) {
				if ($item['name'] == $param) {
					unset($params[$key]);
				}
			}
		}
		return $params;
	}

}